import os
import requests
import threading


class ThreadDownLoad(threading.Thread):

    def __init__(self, load_dict, thread):
        threading.Thread.__init__(self)
        self.load_dict = load_dict
        self.thread = thread

    def run(self):
        print("线程"+str(self.thread)+"开始")
        ThreadDownLoad.down_load_pic(self, self.load_dict)
        print("线程" + str(self.thread) + "结束")

    def down_load_pic(self, load_dict):
        title = load_dict["title"]
        if(title.find("/")>-1):
            title = title.replace("/", "")
        print("文件开始下载:"+title)
        lib = "D:\set/"
        if not os.path.exists(lib):
            os.makedirs(lib)

        pic_list = load_dict["pic_list"]
        i = 0
        for pic in pic_list:
            content = self.send_request(pic, "content")
            file_path = lib + title + pic[-15:-4] +".jpg"
            i += 1
            file = open(file_path, "wb")
            file.write(content)
            file.close()
        print("文件下载结束")

    def send_request(self, url, types):  # 发送链接
        if types is None:
            types = "text"
        response = requests.get(url)
        try:
            if response.status_code == 200:
                print("请求成功:" + url)
                if types == "text":
                    response.encoding = "UTF-8"
                    return response.text
                return response.content
            else:
                print("链接失败")
        except IOError:
            print("链接错误")

if __name__ == "__main__":
    context = ThreadDownLoad.send_request(ThreadDownLoad(),"http://www.lvdou15.com/?ref=chrome","text")